package com.dhecp.project.system.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dhecp.common.config.Global;
import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.enums.PageTemplate;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.service.ButtonStateService;
import com.dhecp.project.system.domain.SysRoleInfo;
import com.dhecp.project.system.mapper.YsDictMapper;
import com.dhecp.project.system.service.SysRoleInfoService;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * 首页 业务处理
 * 
 * @author ruoyi
 */
@Controller
public class SysIndexController extends BaseController
{

	@Autowired
	private YsDictMapper ysDictMapper;
    @Autowired
    private SysRoleInfoService roleInfoService;

	@Autowired
	private ButtonStateService buttonStateService;
	
    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap, ServletRequest request, ServletResponse response) throws IOException {
    	//从配置文件中取配置信息
        //mmap.put("projectName", Global.getName());
        mmap.put("copyrightYear", Global.getCopyrightYear());
        mmap.put("version", "V" + Global.getVersion());
        if(ShiroUtils.getSystemSet() == null){
            ShiroUtils.clearCachedAuthorizationInfo();
            ShiroUtils.getSubject().logout();
            WebUtils.issueRedirect(request, response, "/login");
        }
        //从数据库中取配置信息
        mmap.put("projectName", (ShiroUtils.getSystemSet() != null) ? ShiroUtils.getSystemSet().getSystemName() : ""); //系统名称
        //mmap.put("version", "V" + ShiroUtils.getSystemSet().getSystemVersion()); //系统版本号
        //mmap.put("copyrightYear", ShiroUtils.getSystemSet().getCopyRightYear()); //系统版本年份
        //当前登录用户名
        mmap.put("userName", ShiroUtils.getUserName());
        mmap.put("indexLogo", (ShiroUtils.getSystemSet() != null && StringUtils.isNoneEmpty(ShiroUtils.getSystemSet().getSystemLogo())) ? ShiroUtils.getSystemSet().getSystemLogo() : "/img/logo-v2.png");//获取首页logo
        Map<String, Object> buttonState = new HashMap<String, Object>();
        buttonState.put("moduleTable", "TS_MenuInfo");
        buttonState = buttonStateService.getButtonStateObjectForUser(buttonState);	//按钮状态：（可用：enable，禁用：disable，隐藏：hidden）

        //buttonState.put("vtype","role");
        //buttonState.put("pid",ShiroUtils.getUserId());
        //List<SysUserAndRoleButtonState> list = userAndRoleButtonStateService.queryButtonState(buttonState);


        mmap.put("buttonState", TypeUtils.mapToJson(buttonState));	//按钮状态：（可用：enable，禁用：disable，隐藏：hidden）


        //mmap.put("eknowAiBtn",buttonState.get("eknowai").equals("enable")?true:false);
        IndexDto dto = null;
        {
        	String urlAdmin = Global.getUrlAdmin();
        	String userId = ShiroUtils.getUserId();
        	String passwordEncryped = ShiroUtils.getUserPass();
        	Integer numTackNeedHandle = ysDictMapper.countNumTackNeedHandle(userId);
        	dto = new IndexDto(urlAdmin, userId, passwordEncryped, numTackNeedHandle);
        }
        mmap.put("dto", dto);
        return "index";
    }
	@Data
	@AllArgsConstructor
	private static class IndexDto{
		private String urlAdmin;
		private String userId; // 用户ID
		private String passwordEncryped; // 登录密码（加密）
		private Integer numTackNeedHandle; // 待处理任务数
	}

    // 系统介绍
    @GetMapping("/system/main")
    public String main(ModelMap mmap) throws NoSuchMethodException {
        mmap.put("version", Global.getVersion());
        /*获取当前用户角色信息*/
        String positionName = ShiroUtils.getSysUser().getPositionName();
        String pageTemplateUrl = "";
        if(positionName == null ||"".equals(positionName)){
            pageTemplateUrl = "main-common";
        }else{
            SysRoleInfo sysRoleInfo = roleInfoService.findRoleByRoleName(ShiroUtils.getSysUser().getPositionName());
            String pageTemplate = sysRoleInfo.getPageTemplate();
            if (pageTemplate == null ||"".equals(pageTemplate) ){
                pageTemplateUrl = "main-common";
            }else {
                Map<String, Object> pageTemplateMap = TypeUtils.EnumToMap(PageTemplate.class);
                for (Map.Entry<String, Object> entry : pageTemplateMap.entrySet()) {
                    String mapKey = entry.getKey();
                    String mapVal = entry.getValue().toString();
                    if(mapVal.equals(pageTemplate))pageTemplateUrl = mapKey;
                }
            }
        }
        
        IndexDto dto = null;
        {
        	String urlAdmin = Global.getUrlAdmin();
        	String userId = ShiroUtils.getUserId();
        	String passwordEncryped = ShiroUtils.getUserPass();
        	Integer numTackNeedHandle = ysDictMapper.countNumTackNeedHandle(userId);
        	dto = new IndexDto(urlAdmin, userId, passwordEncryped, numTackNeedHandle);
        }
        mmap.put("dto", dto);
        return pageTemplateUrl;
    }

    //cs登录无授权页面
    @GetMapping("/csunauth")
    public String csUnAuth(ModelMap mmap)
    {
        mmap.put("projectName", Global.getName());
        return "error/csunauth";
    }

    /**
     * 验证登录状态
     * @author XDH
     */
    @RequestMapping("/checkLogin")
    @ResponseBody
    public AjaxResult checkLogin() {
        AjaxResult ajaxResult = new AjaxResult();
        
        if (ShiroUtils.getSystemSet() == null) {
        	ajaxResult = AjaxResult.error("登录过期，请重新登录");
		} else {
			ajaxResult = AjaxResult.success();
		}
        return ajaxResult;
    }
}
